#!/usr/local/bin/python
#take output of combine_outdock_merge plus list of mddr_binders plus list with codes of binders in test set

import sys, string, os


#output from outdock_score.py
input_file = open(sys.argv[1], 'r')
#output from outdock_score.py for second set
input_file_2 = open(sys.argv[2], 'r')
#list with ligands 
input_file_3 = open(sys.argv[3], 'r')

output_file = open(sys.argv[4], 'w')



#------------------------------------
def read_input(dict,afile):

   for i in afile.xreadlines():
     line = ''
     #format correctly, I just need name, rank, score 
     for j in range (1,4):
       #print "number " + str(i.count('\t'))
       pos = i.find('\t')
       #print pos
       line = line + i[:pos] + '\t'
       #print line
       i = i[pos+1:]
       #print i
       
    
     #print line
     name, rank, score = string.split(line[0:-1], '\t')
     rank = float(rank)
     if rank <> 999999:
       dict[name] = float(score)
   afile.close()
   return dict
   
#------------------------------------
   
def sort_func(a,b):
   if a[sort_element] < b[sort_element] :
     return -1
   elif a[sort_element] == b[sort_element]:
     return 0
   else:
     return 1
#------------------------------------
   
dict_1 = {}   

dict_1 =read_input(dict_1, input_file)
dict_1 = read_input(dict_1, input_file_2)




#read labels in list

label_list = []

for i in input_file_3.xreadlines():
  label = string.strip(i)
  label_list.append(label)
  
input_file_3.close()

#labels = dict_2.keys()
#for i in labels:
  #label_list.append(i)
  
all_labels = label_list 

#print all_labels
  
#dict2list
out_list = []
for i in dict_1:
  out_list.append([i, dict_1[i]])


sort_element = 1
out_list.sort(sort_func) 

counter = 1
for i in out_list:
  i.append(counter)
  counter = counter + 1
  

binders = []
for i in out_list:
  if i[0] in all_labels:
    binders.append(i)
    
total = float(len(dict_1))
total_binders = float(len(binders))
counter = 0
per_known_old = 0



for i in binders:
  counter = counter + 1
  #print counter
  #print total_binders
    
  per_knowns = counter / total_binders * 100
  #print per_knowns
  per_database = i[2] / total * 100

  line =  str(per_database) + '\t' + str(per_knowns) + '\t' + i[0] + '\t' + str(i[2])+'\n'
  output_file.write(line)
   
    
  per_known_old = per_knowns
  per_database_old = per_database
  
output_file.close()
